package com.example.demo

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.security.crypto.password.StandardPasswordEncoder


@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Autowired
    lateinit var userDetailService: UserDetailsService

    @Bean
    fun encoder(): PasswordEncoder? {
        return StandardPasswordEncoder("53cr3t")
    }

    override fun configure(http: HttpSecurity?) {
        // 保护请求
        http?.let {
            http.authorizeRequests()
                    .antMatchers("/h2/**").access("permitAll")
                    .antMatchers("/design", "orders")
                    .access("hasRole('ROLE_USER')") // 只有拥有特定权限才允许访问
                    .antMatchers("/", "/**").access("permitAll")
                    .and()
                    .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/design")
                    .and()
                    .logout()
                    .logoutSuccessUrl("/") // 退出登录的时候回到主界面

            //TODO: 生产环境中应该删除
            http.csrf()?.disable()
            http.headers().frameOptions().disable()
        }

    }


    override fun configure(auth: AuthenticationManagerBuilder?) {
        // 识别用户
        auth?.userDetailsService(this.userDetailService)?.passwordEncoder(encoder())
    }
}